package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"novel-mgr1/cache"
	"novel-mgr1/model"
	"time"

	"novel-mgr1/userrpc/internal/svc"
	"novel-mgr1/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CommentListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCommentListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CommentListLogic {
	return &CommentListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 评论列表
func (l *CommentListLogic) CommentList(in *userrpc.CommentListRequest) (*userrpc.CommentListResponse, error) {
	// todo: add your logic here and delete this line
	var findNovel model.Novel
	key := fmt.Sprintf("comment%v", in.Nid)
	err := findNovel.FindNovelById(model.DB, in.Nid)
	if err != nil {
		return nil, err
	}
	if findNovel.ID == 0 {
		return nil, errors.New("作品不存在")
	}
	var novel model.Novel
	var show1 []*userrpc.CommentList
	show := novel.NovelShow(model.DB, in.Nid)
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result == "" {
		show1 = model.CommentList(model.DB, in)
		marshal, _ := json.Marshal(show1)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*10)
	} else {
		json.Unmarshal([]byte(result), &show1)
	}

	return &userrpc.CommentListResponse{
		Uid:        show.Uid,
		NickName:   show.NickName,
		NovelTitle: show.NovelTitle,
		NovelClass: show.NovelClass,
		NovelInfo:  show.NovelInfo,
		List:       show1,
	}, nil
}
